﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

namespace AIC_PN
{
    public partial class BaoCaoMau17_Update : MyFromBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckPermission();
            if (!IsPostBack)
            {
                BindDataToControls();
                if (Request.QueryString["KyBaoCao"] != null)
                {
                    cboKyBaoCao.SelectedValue = Request.QueryString["KyBaoCao"];
                    cboKyBaoCao_SelectedIndexChanged(sender, e);
                }
            }



        }

        /// <summary>
        /// Thủ tục kiểm tra quyền sử dụng của người dùng có được quyền truy cập vào mục này hay không?
        /// </summary>
        private void CheckPermission()
        {
            Dictionary<string, int> Role = MyCommon.CheckPermission("BaoCaoMau1");
            if (Role == null || Role["Xem"] == 0 || ((Role["Xem"] == 1 && Role["Sua"] == 0)))
            {
                Response.Redirect("Index.aspx?p=0");
            }
        }

        /// <summary>
        /// Bind Data vào các contrls như Combobox, ListBox, textBox ...
        /// </summary>
        private void BindDataToControls()
        {
            //TODO
            if (Session["userid"] != null)
            {
                string sql = "Select DV.* " +
                             "From tblDonVi DV " +
                             "Inner Join tblUser U On U.DonViID=DV.ID " +
                             "Where U.ID=" + Session["userid"];
                DataTable dtDV = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
                tdTenDonVi.InnerHtml = "<b><i>Đơn vị báo cáo : " + dtDV.Rows[0]["TenDV"] + "</i></b>";
                sql = "Select ID,TenDM From tblDanhMuc Where MaDM='" + MyConst.DanhMuc.KyBaoCao.Ma + "' ";
                SqlDataReader reKyBaoCao = SqlHelper.ExecuteReader(CommandType.Text, sql);
                clsDataBind.CreateCombo("Tất cả", reKyBaoCao, cboKyBaoCao, 1, 0);
            }
        }

        protected void BindDataToTextField()
        {
            string sql = "SELECT CM_TenBaoCao FROM dbo.tblBaoCaoMau17 WHERE KyBaoCaoID_DM = @KyBaoCaoID_DM AND DonViID = @DonViID AND IsCommon = 1";
            List<SqlParameter> lstParameters = new List<SqlParameter>();
            lstParameters.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, cboKyBaoCao.SelectedValue));
            lstParameters.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, MyCommon.GetDonViID(Session["userid"].ToString())));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql, lstParameters);
            if (dt.Rows.Count != 0)
            {
                txtTenBaoCao.Text = dt.Rows[0]["CM_TenBaoCao"].ToString();
            }
        }

        /// <summary>
        /// Bind Data vào gridview
        /// </summary>
        private void BindDataToGrid()
        {
            List<SqlParameter> lstParams = new List<SqlParameter>();
            lstParams.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, cboKyBaoCao.SelectedValue));
            lstParams.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, Session["userdonvi"]));
            lstParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, Session["userid"]));

            string sql = "SELECT M1.ID,M1.KyBaoCaoID_DM,M1.DonViID,M1.TenBaoCaoID_DM,M1.F1,M1.F2,M1.F3,M1.F4,M1.F5,M1.F6,M1.F7,M1.F8,M1.F9,M1.F10,M1.F11,M1.UserID,A.TenDM,(CASE WHEN A.STT=0 THEN '' ELSE A.STT END) AS STT " +
            "FROM dbo.tblBaoCaoMau17 M1 INNER JOIN dbo.tblDanhMucBaoCao A ON M1.TenBaoCaoID_DM = A.ID " +
            "WHERE KyBaoCaoID_DM = @KyBaoCaoID_DM AND DonViID = @DonViID";
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, sql, lstParams);
            grvData.DataSource = dt;
            grvData.DataBind();
            btnLuu.Visible = true;
            grvData.Visible = true;
        }

        public void MergeRows(GridView gridView)
        {
            for (int rowIndex = gridView.Rows.Count - 2; rowIndex >= 0; rowIndex--)
            {
                GridViewRow row = gridView.Rows[rowIndex];
                GridViewRow previousRow = gridView.Rows[rowIndex + 1];
                if (row.Cells[0].Text == previousRow.Cells[0].Text)
                {
                    row.Cells[0].RowSpan = previousRow.Cells[0].RowSpan < 2 ? 2 : previousRow.Cells[0].RowSpan + 1;
                    previousRow.Cells[0].Visible = false;
                }
            }

        }

        #region Events

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("Index.aspx");
        }

        protected void cboKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboKyBaoCao.SelectedIndex > 0)
            {
                btnLuu.Visible = false;
                grvData.Visible = false;
                grvData.EditIndex = -1;
                BindDataToGrid();
                if (((DataTable)grvData.DataSource).Rows.Count == 0)
                {
                    SqlTransaction MyTran = SqlHelper.BeginTransaction();
                    try
                    {
                        List<SqlParameter> lstParams = new List<SqlParameter>();
                        lstParams.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, cboKyBaoCao.SelectedValue));
                        lstParams.Add(SqlHelper.CreateParameterObject("@DonViID", SqlDbType.Int, ParameterDirection.Input, Session["userdonvi"]));
                        lstParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, Session["userid"]));
                        string sql = "INSERT INTO dbo.tblBaoCaoMau17( KyBaoCaoID_DM ,DonViID ,TenBaoCaoID_DM ,F1,F2,F3,F4,F5,F6,F7,F8,F9,F10,F11,IsCommon,UserID)   " +
                                 "SELECT @KyBaoCaoID_DM ,@DonViID ,B.ID,0,0,0,0,0,0,0,0,0,0,0,0,@UserID FROM dbo.tblDanhMucBaoCao B " +
                                 "WHERE B.MaDM = 100";
                        SqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sql, lstParams);
                        sql = "INSERT INTO dbo.tblBaoCaoMau17(KyBaoCaoID_DM,DonViID,IsCommon ,UserID) " +
                              "VALUES( @KyBaoCaoID_DM,@DonViID,1,@UserID)";
                        SqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sql, lstParams);
                        MyTran.Commit();
                    }
                    catch
                    {
                        MyTran.Rollback();
                    }
                    grvData.EditIndex = -1;
                    BindDataToGrid();
                }
                else
                {
                    BindDataToTextField();
                    grvData.Visible = true;
                }
            }
            else
            {
                btnLuu.Visible = false;
                grvData.Visible = false;

            }
        }

        protected void btnLuu_Click(object sender, EventArgs e)
        {

            string sSQL = "Update tblBaoCaoMau17 Set CM_TenBaoCao=@CM_TenBaoCao" +
                            " Where IsCommon=1 And DonViID=" + MyCommon.GetDonViID(Session["userid"].ToString()) + " And KyBaoCaoID_DM=" + cboKyBaoCao.SelectedValue;

            List<SqlParameter> lstParameter = new List<SqlParameter>();
            lstParameter.Add(SqlHelper.CreateParameterObject("@CM_TenBaoCao", SqlDbType.NVarChar, ParameterDirection.Input, txtTenBaoCao.Text.Trim()));


            SqlHelper.ExecuteNonQuery(CommandType.Text, sSQL, lstParameter);

            MyCommon.AddMessage(this.Master, "Cập nhật báo cáo thành công !", MyConst.MessageType.Success);

        }

        #endregion Events


        #region GridCommand

        private static void AddMergedCells(GridViewRow objgridviewrow, TableCell objtablecell, int colspan, int rowspan, string celltext)
        {
            objtablecell = new TableCell();
            objtablecell.Text = celltext;
            objtablecell.ColumnSpan = colspan;
            objtablecell.RowSpan = rowspan;
            objtablecell.HorizontalAlign = HorizontalAlign.Center;
            objgridviewrow.Cells.Add(objtablecell);
        }

        protected void grvData_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {

                GridView objGridView = (GridView)sender;
                //GridViewRow objgridviewrow = new GridViewRow(1, 0, DataControlRowType.Header, DataControlRowState.Insert);

                GridViewRow objgridviewrow = new GridViewRow(1, 0, DataControlRowType.Header, DataControlRowState.Insert);
                GridViewRow objgridviewrow2 = new GridViewRow(1, 0, DataControlRowType.Header, DataControlRowState.Insert);

                TableCell objtablecell = new TableCell();
                AddMergedCells(objgridviewrow, objtablecell, 1, 2, "TT");
                AddMergedCells(objgridviewrow, objtablecell, 1, 2, "Chỉ tiêu (thống kê chỉ tiêu nữ trên tổng số nam và nữ)");
                AddMergedCells(objgridviewrow, objtablecell, 3, 1, "Giai đoạn trước");
                AddMergedCells(objgridviewrow, objtablecell, 3, 1, "Năm " + DateTime.Now.Year);
                AddMergedCells(objgridviewrow, objtablecell, 2, 1, "So với KHHĐ");
                AddMergedCells(objgridviewrow, objtablecell, 3, 1, "Quy hoạch giai đoạn tới");
                AddMergedCells(objgridviewrow, objtablecell, 1, 2, "Sửa");
                objgridviewrow.BackColor = System.Drawing.Color.FromArgb(0x10, 0x9A, 0xEA);
                objgridviewrow.ForeColor = System.Drawing.Color.White;
                objgridviewrow.Font.Bold = true;
                objGridView.Controls[0].Controls.AddAt(0, objgridviewrow);

                objtablecell = new TableCell();
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Số nữ");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Tổng số (nam và nữ)");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Tỷ lệ (%)");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Số nữ");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Tổng số (nam và nữ)");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Tỷ lệ (%)");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Tăng (%)");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Giảm (%)");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Số nữ");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Tổng số (nam và nữ)");
                AddMergedCells(objgridviewrow2, objtablecell, 1, 1, "Tỷ lệ (%)");
                objgridviewrow2.BackColor = System.Drawing.Color.FromArgb(0x10, 0x9A, 0xEA);
                objgridviewrow2.ForeColor = System.Drawing.Color.White;
                objgridviewrow2.Font.Bold = true;
                objGridView.Controls[0].Controls.AddAt(1, objgridviewrow2);
            }
        }

        protected void grvData_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //if (e.Row.RowType == DataControlRowType.Header)
            //{
            //    e.Row.Cells[0].ColumnSpan = 2;
            //    e.Row.Cells[1].Visible = false;
            //}
            //if (e.Row.RowType == DataControlRowType.DataRow)
            //{
            //    DataRowView dtr = (DataRowView)e.Row.DataItem;
            //    if (e.Row.Cells[0].Text.Equals(e.Row.Cells[1].Text))
            //    {
            //        e.Row.Cells[0].ColumnSpan = 2;
            //        e.Row.Cells[0].Text = (dtr.Row.ItemArray[11].ToString().Equals("0") ? "" : dtr.Row.ItemArray[11].ToString() + ". ") + e.Row.Cells[0].Text;
            //        e.Row.Cells[0].Font.Bold = !dtr.Row.ItemArray[11].ToString().Equals("0") ? true : false;
            //        e.Row.Cells[1].Visible = false;
            //    }
            //    string[] BoiDen = dtr.Row.ItemArray[10].ToString().Split(',');
            //    if (BoiDen.Length >= 1)
            //    {
            //        if (!BoiDen[0].Equals(""))
            //        {
            //            for (int i = 0; i < BoiDen.Length; i++)
            //            {

            //                e.Row.Cells[Convert.ToInt32(BoiDen[i]) + 1].BackColor = System.Drawing.Color.LightGray;
            //                e.Row.Cells[Convert.ToInt32(BoiDen[i]) + 1].Enabled = false;
            //            }
            //        }
            //    }
            //}
            RowDataBound(sender, e);
        }

        protected void grvData_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string sID = e.CommandArgument.ToString().Trim();
            string sCommandName = e.CommandName;

            if ((sCommandName == AIC_PN.MyConst.Action.Approve))
            {
                List<SqlParameter> arrParams = new List<SqlParameter>();
                TextBox txtF1 = (TextBox)grvData.Rows[grvData.EditIndex].Cells[2].Controls[0];
                TextBox txtF2 = (TextBox)grvData.Rows[grvData.EditIndex].Cells[3].Controls[0];
                //TextBox txtF3 = (TextBox)grvData.Rows[grvData.EditIndex].Cells[4].Controls[0];
                TextBox txtF4 = (TextBox)grvData.Rows[grvData.EditIndex].Cells[5].Controls[0];
                TextBox txtF5 = (TextBox)grvData.Rows[grvData.EditIndex].Cells[6].Controls[0];
                //TextBox txtF6 = (TextBox)grvData.Rows[grvData.EditIndex].Cells[7].Controls[0];
                TextBox txtF7 = (TextBox)grvData.Rows[grvData.EditIndex].Cells[8].Controls[0];
                TextBox txtF8 = (TextBox)grvData.Rows[grvData.EditIndex].Cells[9].Controls[0];
                TextBox txtF9 = (TextBox)grvData.Rows[grvData.EditIndex].Cells[10].Controls[0];
                TextBox txtF10 = (TextBox)grvData.Rows[grvData.EditIndex].Cells[11].Controls[0];
                //TextBox txtF11 = (TextBox)grvData.Rows[grvData.EditIndex].Cells[12].Controls[0];
                arrParams.Add(SqlHelper.CreateParameterObject("@F1", SqlDbType.Float, ParameterDirection.Input, Convert.ToInt32(txtF1.Text)));
                arrParams.Add(SqlHelper.CreateParameterObject("@F2", SqlDbType.Float, ParameterDirection.Input, Convert.ToInt32(txtF2.Text)));
                //arrParams.Add(SqlHelper.CreateParameterObject("@F3", SqlDbType.Float, ParameterDirection.Input, Convert.ToInt32(txtF3.Text)));
                arrParams.Add(SqlHelper.CreateParameterObject("@F4", SqlDbType.Float, ParameterDirection.Input, Convert.ToInt32(txtF4.Text)));
                arrParams.Add(SqlHelper.CreateParameterObject("@F5", SqlDbType.Float, ParameterDirection.Input, Convert.ToInt32(txtF5.Text)));
                //arrParams.Add(SqlHelper.CreateParameterObject("@F6", SqlDbType.Float, ParameterDirection.Input, Convert.ToInt32(txtF6.Text)));
                arrParams.Add(SqlHelper.CreateParameterObject("@F7", SqlDbType.Float, ParameterDirection.Input, Convert.ToInt32(txtF7.Text)));
                arrParams.Add(SqlHelper.CreateParameterObject("@F8", SqlDbType.Float, ParameterDirection.Input, Convert.ToInt32(txtF8.Text)));
                arrParams.Add(SqlHelper.CreateParameterObject("@F9", SqlDbType.Float, ParameterDirection.Input, Convert.ToInt32(txtF9.Text)));
                arrParams.Add(SqlHelper.CreateParameterObject("@F10", SqlDbType.Float, ParameterDirection.Input, Convert.ToInt32(txtF10.Text)));
                //arrParams.Add(SqlHelper.CreateParameterObject("@F11", SqlDbType.Float, ParameterDirection.Input, Convert.ToInt32(txtF11.Text)));
                string sql = "UPDATE tblBaoCaoMau17 SET [F1]=@F1,[F2]=@F2,[F3]=(CASE WHEN @F2<>0 THEN (@F1/@F2)*100 ELSE 0 END),[F4]=@F4," +
                                "[F5]=@F5,[F6]=(CASE WHEN @F5<>0 THEN (@F4/@F5)*100 ELSE 0 END),[F7]=@F7,[F8]=@F8,[F9]=@F9,[F10]=@F10," +
                                "[F11]=(CASE WHEN @F10<>0 THEN (@F9/@F10)*100 ELSE 0 END),[UpdateDate]=GETDATE(),[UserID]=@UserID WHERE ID=@ID ";
                arrParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, Session["userid"]));
                arrParams.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, Convert.ToInt32(sID)));
                SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
                MyCommon.AddMessage(this.Master, "Cập nhật báo cáo thành công !", MyConst.MessageType.Success);
                grvData.EditIndex = -1;
                BindDataToGrid();
            }
        }

        protected void grvData_RowEditing(object sender, GridViewEditEventArgs e)
        {

            grvData.EditIndex = e.NewEditIndex;
            BindDataToGrid();
        }



        protected void grvData_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            //grvData.PageIndex = e.NewPageIndex;
            //BindDataToGrid();
        }


        protected void grvData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grvData.EditIndex = -1;
            BindDataToGrid();
        }

        #endregion GridCommand

        protected void grvData_PreRender(object sender, EventArgs e)
        {
            MergeRows(grvData);
        }
    }
}
